package com.itmck.config;

import com.alibaba.fastjson.JSONObject;
import com.itmck.component.ApiResultResponse;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Deque;

public class KickoutSessionFilter extends AccessControlFilter {

    private SessionManager sessionManager;
    private Cache<String, Deque<Serializable>> cache;
    private RedisCacheManager redisCacheManager;

    public void setSessionManager(SessionManager sessionManager){
        this.sessionManager = sessionManager;
    }

    public void setCache(RedisCacheManager redisCacheManager){
        this.cache = redisCacheManager.getCache("kickout-session");
        this.redisCacheManager = redisCacheManager;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        Subject subject = getSubject(request,response);
        if (subject == null || !subject.isAuthenticated()) {
            return true;
        }
        Session session = subject.getSession();

        if(session.getAttribute("kickout") != null && (boolean)session.getAttribute("kickout")){
            subject.logout();
            saveRequest(request);
            ApiResultResponse<String> restResult = new ApiResultResponse<>();
            restResult.setErrorCode("1");
            restResult.setMessage("被踢了");

            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            ((DefaultWebSessionManager)this.sessionManager).getSessionDAO().delete(session);
            try (PrintWriter writer = response.getWriter()) {
                writer.print(JSONObject.toJSON(restResult).toString());
                return false;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }

}

